<?php

/**
 * Content form.
 *
 * @package    Amman to London
 * @subpackage form
 * @author     Adel Abu-Saif
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class ContentForm extends BaseContentForm {

    public function configure() {
        unset($this['created_at'], $this['updated_at'], $this['slug']);
        $this->embedI18n(array('en', 'ar'));
        $this->widgetSchema['category_id']->setOption('add_empty', false);
        $this->widgetSchema['ar']->setLabel('Arabic');
        $this->widgetSchema['en']->setLabel('English');
        $this->widgetSchema['image'] = new sfWidgetFormInputFile(array());
        $this->validatorSchema['image'] = new sfValidatorFile(array('required' => false, 'path' => sfConfig::get('sf_web_dir') . '/uploads/images/'));
    }

    public function save($con = null) {
        $obj = parent::save($con);
        /* @var $obj Content */
        $obj->set('slug', ($obj->Translation['en']->title != '' ? self::slugify($obj->Translation['en']->title) : $obj->getId()));
        $obj->save();
        return $obj;
    }

//
//    public static function slugify($text) {
//        // replace non letter or digits by -
//        $text = ereg_replace('/~[^\\pL\d]+~u/', '-', $text);
//
//        // trim
//        $text = trim($text, '-');
//
//        // transliterate
//        if (function_exists('iconv')) {
//            $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
//        }
//
//        // lowercase
//        $text = strtolower($text);
//
//        // remove unwanted characters
//        $text = ereg_replace('/~[^-\w]+~/', '', $text);
//
//        if (empty($text)) {
//            return 'n-a';
//        }
//
//        return $text;
//    }

    public static function slugify($string) {
        $string = utf8_decode($string);
        $string = html_entity_decode($string);

        $a = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ';
        $b = 'AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn';
        $string = strtr($string, utf8_decode($a), $b);

        $ponctu = array("?", ".", "!", ",");
        $string = str_replace($ponctu, "", $string);

        $string = trim($string);
        $string = preg_replace('/([^a-z0-9]+)/i', '-', $string);
        $string = strtolower($string);

        if (empty($string))
            return 'n-a';

        return utf8_encode($string);
    }

}
